package com.wlyuan.open.domain.service.jiajia;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.wlyuan.open.domain.PushBusinessType;
import com.wlyuan.open.domain.PushTask;
import com.wlyuan.open.domain.repository.PushTaskRepository;
import com.wlyuan.open.domain.service.PushStrategy;
import com.wlyuan.open.vo.push.order.AttachmentVO;
import com.wlyuan.open.vo.push.order.OrderDetailVO;
import com.wlyuan.open.vo.push.order.OrderGoodsVO;
import com.wlyuan.open.vo.push.waybill.WaybillPickCovenantDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 加加推送
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class JiaJiaPushStrategy implements PushStrategy {
    private final PushTaskRepository pushTaskRepository;

    @Override
    public void handle(PushTask pushTask) {
        String requestUrl = pushTask.getRequestUrl();
        //根据业务类型，判断请求数据
        var businessType = pushTask.getBusinessType();
        String requestBody = null;
        if (businessType.equals(PushBusinessType.CARRIER_AGREED)) {
           requestBody = JSON.toJSONString(pushTask.getBusinessInfo());
        } else if(businessType.equals(PushBusinessType.WAYBILL_PICK_COVENANT)){
            requestBody = JSON.toJSONString(getWaybillPickCovenantRequestBody(pushTask));
        } else if(businessType.equals(PushBusinessType.ORDER_SIGNED)){
            requestBody = JSON.toJSONString(getOrderSignRequest(pushTask));
        } else if(businessType.equals(PushBusinessType.ORDER_RECEIPT)){
            OrderRequest orderRequest = getOrderReceiptRequest(pushTask);
            if(orderRequest!=null) {
                requestBody = JSON.toJSONString(orderRequest);
            }
        } else if(businessType.equals(PushBusinessType.ORDER_SCORED)){
            OrderScoreRequest scoreRequest = getOrderScore(pushTask);
            if(scoreRequest!=null) {
                requestBody = JSON.toJSONString(scoreRequest);
            }
        }
        sendPost(requestUrl,requestBody,pushTask);
        pushTaskRepository.save(pushTask);
    }


    private OrderScoreRequest getOrderScore(PushTask task){
        OrderDetailVO order = JSON.toJavaObject(task.getBusinessInfo(), OrderDetailVO.class);
        if(order.getScore()!=null) {
            OrderScoreRequest scoreRequest = new OrderScoreRequest();
            scoreRequest.setTenantId(task.getTenantId());
            OrderScoreRequest.ScoreOrder scoreOrder = scoreRequest.new ScoreOrder();
            scoreOrder.setOrderId(order.getOrderId());
            scoreOrder.setScore(order.getScore().getStar());
            StringBuilder scoreDesc =new StringBuilder("");
            if(CollectionUtil.isNotEmpty(order.getScore().getLabels())){
                scoreDesc.append(StringUtils.join(order.getScore().getLabels(),","));
            }
            if(StringUtils.isNotBlank(order.getScore().getRemarks())) {
                if(StringUtils.isNotBlank(scoreDesc)){
                    scoreDesc.append(";");
                }
                scoreDesc.append(order.getScore().getRemarks());
            }
            scoreOrder.setScoreDesc(scoreDesc.toString());
            scoreRequest.setOrder(scoreOrder);
            return scoreRequest;
        }
        return null;
    }


    private OrderRequest getOrderReceiptRequest(PushTask task){
        OrderRequest receiptRequest = new OrderRequest();
        OrderDetailVO order = JSON.toJavaObject(task.getBusinessInfo(),OrderDetailVO.class);
        receiptRequest.setTenantId(order.getTenantId());
        receiptRequest.setUserId(order.getReceipt().getReceiptBy());
        OrderRequest.Order receiptRequestOrder = receiptRequest.new Order();
        receiptRequestOrder.setOrderId(order.getOrderId());
        receiptRequestOrder.setReceiptAt(order.getReceipt().getReceiptTime());
        receiptRequestOrder.setReceiptSignTime(order.getReceipt().getReceiptSignTime());
        List<OrderRequest.OrderGoods> receiptGoodsList = new ArrayList<>(order.getGoodsList().size());
        OrderRequest.OrderGoods goods = null;
        OrderRequest.OrderGoodsSignReceiptDetail goodsReceipt = null;
        for(OrderGoodsVO orderGoodsVO:order.getGoodsList()){
            goods = receiptRequest.new OrderGoods();
            goods.setGoodsId(orderGoodsVO.getGoodsId());
            goods.setEcho(orderGoodsVO.getEcho());
            goodsReceipt = receiptRequest.new OrderGoodsSignReceiptDetail();
            BeanUtils.copyProperties(orderGoodsVO.getReceipt(),goodsReceipt);
            goodsReceipt.setDesc(orderGoodsVO.getReceipt().getRemarks());
            goods.setGoodsReceipt(goodsReceipt);
            receiptGoodsList.add(goods);
        }
        receiptRequestOrder.setGoodsList(receiptGoodsList);
        List<OrderRequest.OrderAttachment> attachments = new ArrayList<>(order.getReceipt().getAttachments().size());
        OrderRequest.OrderAttachment attachment = null;
        for(AttachmentVO attachDTO:order.getReceipt().getAttachments()){
            attachment = receiptRequest.new OrderAttachment();
            BeanUtils.copyProperties(attachDTO,attachment);
            attachments.add(attachment);
        }
        receiptRequestOrder.setAttachments(attachments);
        receiptRequest.setOrder(receiptRequestOrder);
        return receiptRequest;
    }

    private OrderRequest getOrderSignRequest(PushTask task){
        OrderRequest signRequest = new OrderRequest();
        OrderDetailVO order = JSON.toJavaObject(task.getBusinessInfo(),OrderDetailVO.class);
        signRequest.setTenantId(order.getTenantId());
        signRequest.setUserId(order.getSign().getSignBy());
        OrderRequest.Order signRequestOrder = signRequest.new Order();
        signRequestOrder.setOrderId(order.getOrderId());
        signRequestOrder.setSignType(order.getSign().getSignType());
        signRequestOrder.setSignAt(order.getSign().getSignAt());
        signRequestOrder.setSignDesc(order.getSign().getRemarks());
        List<OrderRequest.OrderGoods> signGoodsList = new ArrayList<>(order.getGoodsList().size());
        OrderRequest.OrderGoods goods = null;
        OrderRequest.OrderGoodsSignReceiptDetail goodsSign = null;
        for(OrderGoodsVO orderGoodsVO:order.getGoodsList()){
            goods = signRequest.new OrderGoods();
            goods.setGoodsId(orderGoodsVO.getGoodsId());
            goods.setEcho(orderGoodsVO.getEcho());
            goodsSign = signRequest.new OrderGoodsSignReceiptDetail();
            BeanUtils.copyProperties(orderGoodsVO.getSign(),goodsSign);
            goodsSign.setDesc(orderGoodsVO.getSign().getRemarks());
            goods.setGoodsSign(goodsSign);
            signGoodsList.add(goods);
        }
        signRequestOrder.setGoodsList(signGoodsList);
        List<OrderRequest.OrderAttachment> attachments = new ArrayList<>(order.getSign().getAttachments().size());
        OrderRequest.OrderAttachment attachment = null;
        for(AttachmentVO attachDTO:order.getSign().getAttachments()){
            attachment = signRequest.new OrderAttachment();
            BeanUtils.copyProperties(attachDTO,attachment);
            attachments.add(attachment);
        }
        signRequestOrder.setAttachments(attachments);
        //评分
        if(order.getScore()!=null){
            OrderRequest.OrderScore orderScore = signRequest.new OrderScore();
            orderScore.setScore(order.getScore().getStar());
            StringBuilder scoreDesc = new StringBuilder("");
            if(CollectionUtil.isNotEmpty(order.getScore().getLabels())){
                scoreDesc.append(StringUtils.join(order.getScore().getLabels(),","));
            }
            if(StringUtils.isNotBlank(order.getScore().getRemarks())) {
                if(StringUtils.isNotBlank(scoreDesc)){
                    scoreDesc.append(";");
                }
                scoreDesc.append(order.getScore().getRemarks());
            }
            orderScore.setScoreDesc(scoreDesc.toString());
            signRequestOrder.setScore(orderScore);
        }
        signRequest.setOrder(signRequestOrder);
        return signRequest;
    }

    private WaybillPickCovenantRequest getWaybillPickCovenantRequestBody(PushTask task){
        WaybillPickCovenantRequest body = new WaybillPickCovenantRequest();
        var detail = JSON.toJavaObject(task.getBusinessInfo(), WaybillPickCovenantDetailVO.class);
        BeanUtils.copyProperties(detail,body);
        body.setCarNo(detail.getPlateNo());
        body.setVehicleWeight(detail.getVehicleWeight().toString());
        return body;
    }

    private void sendPost(String requestUrl, String requestBody, PushTask pushTask){
        if(StringUtils.isNotBlank(requestBody)&&StringUtils.isNotBlank(requestUrl)) {
            try {
                HttpRequest request = HttpRequest.post(requestUrl);
                request.body(requestBody, "application/json");
                HttpResponse response = request.execute();
                JSONObject data = JSONUtil.parseObj(response.body());

                if (response.isOk()) {
                    if (data != null) {
                        Integer code = data.getInt("code");
                        if (code == 0) {
                            pushTask.success(requestUrl, requestBody, data.toString());
                        } else {
                            pushTask.fail(requestUrl, requestBody, data.toString(), data.getStr("message"));
                        }
                    }
                }
            } catch (Exception ex) {
                logger.error("推送{}失败：{}", pushTask.getBusinessType().getName(), ex);
                pushTask.fail(requestUrl, requestBody, null, ex.getMessage());
            }
        }else{
            pushTask.fail(requestUrl,requestBody,null,"请求地址或请求参数为空");
        }
    }


}
